#!/bin/bash
# 两个目录中的文件去重

function fn_get_size_fname()
{
   local dir_name="$1"
   find "${dir_name}" -type f -print0 |xargs -0 ls -lSQ |sed -r 's/^([^ ]+ +){4}//g;s/^([0-9]+)[^"]+(.+)/\1:\2/g'
}

function fn_get_size_name_list()
{
   local size_name="$1"
   local i=1
   while :
   do
       local tmp_array[$i]=`echo "${size_name}" |sed -n ''$i'p'`
       eval ${2}[$i]="${tmp_array[$i]}"
       [ -z "${tmp_array[$i]}" ] && { eval "unset ${2}[$i]" ; break ; }
       let i++
   done
   
   eval $2=${lst} 
}

function fn_md5sum()
{
     local file1="${1}"
     local file2="${2//\"/}"
     local file1_md5=`md5sum "${file1}"` || return 101
     local file2_md5=`md5sum "${file2}"` || return 101

     if [ "${file1_md5%% *}" != "${file2_md5%% *}" ]
     then
         echo "$1 not match with $2."
         return 102
     fi
     
     return 0
}

function fn_main()
{
    src="$1"
    dst="$2"
    if [ ! -d "${src}" ] || [ ! -d "${dst}" ] 
    then
        echo -e "\e[1;31mUsage:$0 directory1 directory2" 
        return 100
    fi

    src_size_name=`fn_get_size_fname "${src}"`
    dst_size_name=`fn_get_size_fname "${dst}"`

    fn_get_size_name_list "${src_size_name}" SRC_LST

    for ((i=1;i<${#SRC_LST[@]};i++))
    do
        dst_match=`echo "${dst_size_name}" |grep "^${SRC_LST[$i]%:*}"`
        if [ $? -eq 0 ]
        then
            fn_md5sum "${SRC_LST[$i]#*:}" "${dst_match#*:}"  &&  echo "${SRC_LST[$i]#*:} = ${dst_match#*:}"  
        fi
    done
}

fn_main $@
exit $?
